package cn.zfs.springcloud.controller;

import cn.zfs.springcloud.dao.ESRepository;
import cn.zfs.springcloud.elasticsearchserver.model.ESEntity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @ClassName: ElasticsearchController
 * @Author: ZFS
 * @Date: 2018/9/20 16:55
 */
@RestController
@RequestMapping("es")
@Slf4j
public class ElasticsearchController {

    @Autowired
    private ESRepository esRepository;

    @GetMapping("test1")
    public Object test1() {
        ESEntity esEntity = new ESEntity();
        esEntity.setDescription("test1");
        esEntity.setName("test1_name");
        ESEntity index = esRepository.index(esEntity);
        return "Success";
    }

    @GetMapping("save")
    public Object save() {
        ESEntity esEntity = new ESEntity();
        esEntity.setDescription("save_test");
        esEntity.setName("save_test1_name");
        ESEntity save = esRepository.save(esEntity);
        log.info(JSONObject.toJSONString(save));
        return "Success";
    }

    @GetMapping("get")
    public Object get() {
        Iterable<ESEntity> all = esRepository.findAll();
        QueryBuilder queryBuilder = new QueryBuilder() {
            @Override
            protected void doXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
                params.param("name","save_test1_name");
            }
        };
        Iterable<ESEntity> search = esRepository.search(queryBuilder);
        return all;
    }


}
